<template>
  <div id="addmilk">
    <van-form
      :show-error-message="false"
      show-error
      scroll-to-error
      validate-first
      @failed="onFailed"
      @submit="onSubmit"
    >
      <div>
        <!-- 标题 -->
        <title-panel title="基础信息"></title-panel>
        <!-- 基础信息表单 -->

        <van-field
          required
          readonly
          clickable
          :value="object.salesDate"
          @click="showDateSelect = true"
          name="sellDate"
          label="销售日期"
          :rules="[{ required: true, message: '请选择时间' }]"
          placeholder="请选择时间"
          label-width="10em"
          input-align="right"
          is-link
        >
        </van-field>
        <van-popup v-model="showDateSelect" position="bottom">
          <van-datetime-picker type="date" @confirm="onConfirm" @cancel="showDateSelect = false" v-model="date" />
        </van-popup>
        <van-field
          input-align="right"
          required
          name="sellAmount"
          v-model="object.salesAmount"
          type="number"
          label="销售金额 (元)"
          @keydown="valueChange"
          :rules="[{ required: true, message: '请填写销售金额' }]"
          placeholder="请填写"
          label-width="10em"
        />
        <van-field
          input-align="right"
          @click="inputClick('000')"
          :value="object.whereaboutsEnterpriseName"
          required
          readonly
          clickable
          name="sellTo"
          label="销售去向"
          :rules="[{ required: true, message: '请选择企业' }]"
          placeholder="请选择企业"
          label-width="10em"
          is-link
        >
        </van-field>
        <template v-if="milkStationFlag == 0">
          <van-field
            v-model="number"
            input-align="right"
            required
            name="milkTotalNum"
            :rules="[{ required: true, message: '请填写生鲜乳总数量' }]"
            label="生鲜乳总数量 (kg)"
            type="number"
            :value="0"
            readonly
            label-width="10em"
          />
        </template>
        <template v-else>
          <van-field
            v-model="number"
            input-align="right"
            required
            name="milkTotalNum"
            :rules="[{ required: true, message: '请填写生鲜乳总数量' }]"
            label="生鲜乳总数量 (kg)"
            type="number"
            :value="0"
            label-width="10em"
          />
        </template>
      </div>
      <template v-if="milkStationFlag == 0">
        <!-- 自产信息 -->
        <div>
          <!-- 标题 -->
          <title-panel title="自产信息"></title-panel>
          <!-- 表单 -->

          <van-field
            input-align="right"
            required
            v-model="object.selfFreshMilkTotal"
            name="milkTotalNum2"
            label="生鲜乳数量 (kg)"
            :rules="[{ required: true, message: '请填写生鲜乳总数量' }]"
            type="number"
            @keydown="valueChange1"
            label-width="10em"
            placeholder="请填写"
          />
        </div>
        <!-- 收购明细 -->
        <div>
          <!-- 标题 -->
          <div class="flex-between align-items m-r-5">
            <title-panel title="收购明细" />
            <!-- <van-button  type="primary" native-type="button" class="btn" @click="addItem">
              <img style="width: 8px; height: 8px;position: relative; top: -1px;" src="../../assets/img/xiugai/icon-plus.png" alt="">
              新增
            </van-button> -->
            <div class="btn" @click="addItem"></div>
          </div>
          <!-- 表单 -->
          <div v-for="(item, index) in shouGouDetail" :key="index" style="margin-bottom: 10px">
            <van-field
              input-align="right"
              @click="inputClick(index)"
              required
              readonly
              clickable
              label="生鲜乳来源"
              placeholder="请选择"
              :rules="[{ required: true, message: '请选择' }]"
              label-width="10em"
              v-model="item.sourceEnterpriseName"
              is-link
            >
            </van-field>
            <van-field
              input-align="right"
              required
              readonly
              label="销售批次"
              label-width="10em"
              v-model="item.salesBatchNo"
            />
            <van-field
              input-align="right"
              required
              readonly
              label="生鲜乳总数量"
              type="number"
              label-width="10em"
              v-model="item.freshMilkTotal"
            />
            <van-field readonly input-align="right" center label-width="10em">
              <template #button>
                <!-- <van-button
                  color="#999999"
                  plain
                  type="info"
                  native-type="button"
                  @click="deleteItem(index)"
                  class="delete-btn"
                  >删除</van-button
                > -->
                <div class="delete-btn" @click="deleteItem(index)"></div>
              </template>
            </van-field>
          </div>
        </div>
      </template>
      <div class="add-btn">
        <van-button
          block
          type="info"
          color="#37B5B5"
          style="width: 85%; margin: auto; margin-top: 50px"
          native-type="submit"
          size="large"
          :loading="loading"
          loading-text="提交中..."
          >保存</van-button
        >
      </div>
      <div style="height: 20px"></div>
    </van-form>
  </div>
</template>

<script>
import { Form, Field, DatetimePicker, Popup, Icon, Button, Toast } from 'vant'
import titlePanel from '@/components/titlePanel'
import rightArrow from '@/assets/img/right-arrow.png'
import { getValue } from '@/utils/auth'
import { postHandle } from '@/api'
import dayjs from 'dayjs'
import { setValue } from '../../utils/auth'
export default {
  name: '',
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [DatetimePicker.name]: DatetimePicker,
    [Popup.name]: Popup,
    [Icon.name]: Icon,
    [Button.name]: Button,
    titlePanel
  },
  data() {
    return {
      date: new Date(),
      sellDate: null,
      arr: [],
      showDateSelect: false,
      loading: false,
      milkStationFlag: getValue('milkStationFlag'),
      shouGouDetail: [],
      rightArrow,
      number: null,
      index: null,
      object: {
        tenantCode: getValue('tenantCode'),
        subjectInfoId: getValue('subjectInfoId'),
        whereaboutsEnterpriseId: null,
        whereaboutsEnterpriseName: null,
        salesDate: dayjs(new Date()).format('YYYY-MM-DD'),
        salesAmount: null,
        freshMilkTotal: null,
        selfFreshMilkTotal: null,
        salesIds: null
      }
    }
  },
  watch: {
    object: {
      handler(val) {
        let num = 0
        if (this.shouGouDetail) {
          this.shouGouDetail.forEach(item => {
            num += Number(item.freshMilkTotal)
          })
        }
        this.number = Number(num) + Number(val.selfFreshMilkTotal)
      },
      deep: true
    },
    shouGouDetail: {
      handler(val) {
        let num = 0
        val.forEach(item => {
          if (item.freshMilkTotal) {
            num += Number(item.freshMilkTotal)
          }
        })
        num = Number(num) + Number(this.object.selfFreshMilkTotal)
        this.number = num
      }
    }
  },
  created() {
    this.$bridge.register('refresh', data => {
      const handle = getValue('milk-object-handle')
      if (handle === 'chooseEnterprise') {
        const milk = getValue('milk-object')
        if (milk) {
          const obj = JSON.parse(milk)
          this.object = Object.assign({}, this.object, obj)
        }
        const enterpriseStr = getValue('enterprise-obj')
        if (enterpriseStr) {
          const enterprise = JSON.parse(enterpriseStr)
          this.object.whereaboutsEnterpriseId = enterprise.id
          this.object.whereaboutsEnterpriseName = enterprise.enterpriseName
        }
      }
      if (handle === 'chooseSource') {
        const milk = getValue('milk-object')
        if (milk) {
          const obj = JSON.parse(milk)
          this.object = Object.assign({}, this.object, obj)
        }
        const shouGouDetail = JSON.parse(getValue('milk-shouGouDetail'))
        const index = getValue('milk-index')
        shouGouDetail[index] = JSON.parse(getValue('source-obj'))
        this.shouGouDetail = shouGouDetail
      }
      // callJsMethod("refresh")
    })
  },
  methods: {
    inputClick(index) {
      if (index === '000') {
        setValue('milk-object', JSON.stringify(this.object))
        setValue('milk-object-handle', 'chooseEnterprise')
        this.$bridge.call('enterpriseAdd')
      } else {
        setValue('milk-object', JSON.stringify(this.object))
        setValue('milk-object-handle', 'chooseSource')
        setValue('milk-shouGouDetail', JSON.stringify(this.shouGouDetail))
        setValue('milk-index', index)
        this.$bridge.call('milkSource')
      }
    },
    deleteItem(index) {
      this.shouGouDetail.splice(index, 1)
    },
    addItem() {
      this.shouGouDetail.push({
        id: '',
        salesBatchNo: '',
        freshMilkTotal: ''
      })
    },
    onConfirm(time) {
      this.object.salesDate = dayjs(time).format('YYYY-MM-DD')
      this.showDateSelect = false
    },
    onSave() {
      let arr = []
      this.shouGouDetail.forEach(item => {
        arr.push(item.id)
      })
      this.object.salesIds = arr.toString()
      this.object.freshMilkTotal = this.number
      postHandle(`/agri/api/yzbzh/saleInfo/save`, this.object)
        .then(res => {
          if (res.status === 0) {
            setValue('milk-object', null)
            setValue('milk-object-handle', null)
            setValue('enterprise-obj', null)
            setValue('milk-index', null)
            setValue('milk-shouGouDetail', null)
            setValue('source-obj', null)
            this.$toast.success(res.msg)
            this.loading = false
            this.$bridge.call('base.closePage')
          } else {
            this.$toast.fail(res.msg)
            this.loading = false
          }
        })
        .catch(res => {
          this.$toast(res.msg)
          this.loading = false
        })
    },
    onFailed(errorInfo) {
      Toast(errorInfo.errors[0].message)
    },
    onSubmit(value) {
      this.loading = true
      // let imgInfos = this.obj.imgInfos.map((item) => item.url).join(",");
      // 发送保存网络请求
      this.onSave()
    },
    valueChange(e) {
      e.target.value = e.target.value.match(/^\d*(\.?\d{0,1})/)[0] || null
    },
    valueChange1(e) {
      e.target.value = e.target.value.match(/^\d*(\.?\d{0,1})/)[0] || null
    }
  }
}
</script>

<style lang="scss" scoped>
.delete-btn {
  width: 50px;
  height: 28px;
  border-radius: 4px;
  overflow: hidden;
  background: url(../../assets/img/deletebtn.png);
  background-size: 100% 100%;
}
.title {
  width: 100%;
  height: 50px;
  background-color: transparent;
  align-items: center;
  font-size: 16px;
  color: #333;
  .left-border {
    width: 4px;
    height: 14px;
    background-color: #00b8b6;
    margin-right: 11px;
  }
}
.btn {
  width: 60px;
  height: 28px;
  border-radius: 4px;
  overflow: hidden;
  background: url(../../assets/img/add.png);
  background-size: 100% 100%;
}
</style>
